<?php
require_once 'db.php';

// 设置响应头，确保JSON响应正确
header('Content-Type: application/json');

// 接收表单数据
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';

// 定义响应数据
$response = [
    'status' => false,
    'message' => '登录失败'
];

// 验证输入
if (empty($username) || empty($password)) {
    $response['message'] = '用户名和密码不能为空';
    echo json_encode($response);
    exit;
}

// 检查用户是否存在
$stmt = $conn->prepare("SELECT id, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $response['message'] = '用户名不存在';
    echo json_encode($response);
    exit;
}

// 获取用户信息
$user = $result->fetch_assoc();

// 验证密码
if (!password_verify($password, $user['password'])) {
    $response['message'] = '密码错误';
    echo json_encode($response);
    exit;
}

// 登录成功，创建会话
session_start();
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $username;
$_SESSION['login_time'] = time();

// 登录成功响应
$response['status'] = true;
$response['message'] = '登录成功';
echo json_encode($response);

// 关闭连接
$stmt->close();
$conn->close();
?>
